#include "../include/BST.h"
#include "../include/errorcodes.h"

int create_dir(char *path, char *dirname)
{



	int bstins;
	int testflag=checkNameValidity(dirname);
	if(!testflag)
	{
		return 2;
	}
	
	if(fdcounter>=header.maxNoOfFileDescriptor)
		return 1;



	int result;
    	char *tokens[80]; 
	
	fd *bstReturn;
	char *fullPath;
	fullPath=(char*)malloc(sizeof(char)*100);


	strcpy(fullPath,path);

	if(strcmp(fullPath,"/")!=0)
		strcat(fullPath,"/");

	strcat(fullPath,dirname);
	//printf("%s\n",fullPath);
	

	//Check for path of directory in BST.
	//printf("\nBst contents . . . .\n");
	//print(bstRoot);
	//print(bstRoot);
	bstReturn=bstSearchNode(&bstRoot,fullPath);
	if(bstReturn!=NULL)
		return 3;

	else
	{
		
		//Insert into N-ary tree
		if(strcmp(path,"/")!=0)
		{
			bstReturn=bstSearchNode(&bstRoot,path);
		}
		if(bstReturn!=NULL || strcmp(path,"/")==0)
		{
			//Prepare the fd
			fd *data = (fd*)malloc(sizeof(fd));
			data-> fileType='D';
			data->fileSize= 0;
			strcpy(data->file_name,dirname);
			strcpy(data->path,path);
			result =  insert_node(&naryRoot,data);
			bstins=bstInsertNode(&bstRoot,data);
			hashInsert(hash,*data);

		}
		else
		{
			int j, i=0; 
			char parent_path_temp[100];
			strcpy(parent_path_temp,fullPath);
			tokens[0] = strtok(parent_path_temp, "/"); 
			while(tokens[i]!= NULL) 
			{ 
   
				//printf("TOKEN:::::::::::::%s\n", tokens[i]); 
				i++;
				tokens[i] = strtok(NULL, "/"); 
			}

			char subPath[100];
			char prevPath[100];
			strcpy(subPath,"/");
			for(j = 0; j <= i-1; j++) 
			{
				strcpy(prevPath,subPath);
				if(strcmp(prevPath,"/")!=0)
				{
					strcpy(subPath,prevPath);
					strcat(subPath,"/");
					strcat(subPath,tokens[j]);
				}
				else
				{
					//strcpy(subPath,"/");
					strcat(subPath,tokens[j]);
				}
				
				print(bstRoot);
				bstReturn=bstSearchNode(&bstRoot,subPath);
				if(bstReturn==NULL)
				{
					
					fd *data = (fd*)malloc(sizeof(fd));
					data-> fileType='D';
					data->fileSize= 0;
					strcpy(data->file_name,tokens[j]);
					strcpy(data->path,prevPath);

					
					result =  insert_node(&naryRoot,data);
					bstins=bstInsertNode(&bstRoot,data);
					hashInsert(hash,*data);
				}
			
			}
		}	
		//Is it a Duplicate?	
		if(result == -1)
			return 3;
		
		/*Invalid path for root or node
		if(result==1)
			return ERR_VFS_MAKEDIR_01;*/

	}

	//printf("\nFDcounter=%ld",fdcounter);
	//printtree(naryRoot);
	//Successful return



	return 0;

}
